using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

public class DamagePopupManager : MonoBehaviour
{
    public static DamagePopupManager Instance { get; private set; }

    [Header("运行时自动赋值")]
    public RectTransform canvasRect;
    public Camera uiCamera;
    public DamagePopup popupPrefab;

    private void Awake()
    {
        // Awake 里只做单例保护
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

    /// <summary>
    /// 全局调用：自动创建或复用 Manager，然后弹出飘字
    /// </summary>
    public static void ShowDamage(Vector3 worldPos, int damage, DamageType type)
    {
        // 1. 如果已经有实例直接用
        if (Instance != null)
        {
            Instance.SpawnPopup(worldPos, damage, type);
            return;
        }

        // 2. 场景里搜一遍有没有挂的
        var existing = FindObjectOfType<DamagePopupManager>();
        if (existing != null)
        {
            Instance = existing;
            Instance.SpawnPopup(worldPos, damage, type);
            return;
        }

        // 3. 全自动创建一个新的 Manager
        var go = new GameObject("DamagePopupManager");
        var mgr = go.AddComponent<DamagePopupManager>();

        // 3.1 找到场景中的 Canvas
        var canvas = FindObjectOfType<Canvas>();
        if (canvas == null)
        {
            Debug.LogError("Scene 中找不到 Canvas，请先创建一个 UI Canvas。");
            return;
        }
        mgr.canvasRect = canvas.GetComponent<RectTransform>();

        // 3.2 根据 Canvas 模式自动取 UI Camera
        mgr.uiCamera = (canvas.renderMode == RenderMode.ScreenSpaceCamera)
                      ? canvas.worldCamera
                      : null;

        // 3.3 从 Resources 加载你的 DamagePopup.prefab
        mgr.popupPrefab = Resources.Load<DamagePopup>("DamagePopup");
        if (mgr.popupPrefab == null)
        {
            Debug.LogError("Resources/DamagePopup.prefab 加载失败！");
            Destroy(go);
            return;
        }

        // 3.4 标记常驻并设置单例
        DontDestroyOnLoad(go);
        Instance = mgr;

        // 4. 最后再调用一次
        Instance.SpawnPopup(worldPos, damage, type);
    }

    private void SpawnPopup(Vector3 worldPos, int damage, DamageType type)
    {
        // print("0000---");
        // 世界坐标 → 屏幕坐标
        Vector2 screenPos = worldPos;
        // 屏幕坐标 → Canvas 本地坐标
        RectTransformUtility.ScreenPointToLocalPointInRectangle(
            canvasRect,
            screenPos,
            uiCamera,
            out Vector2 anchoredPos
        );

        // 实例化并播放
        var popup = Instantiate(popupPrefab, canvasRect);
        popup.GetComponent<RectTransform>().anchoredPosition = anchoredPos;
        popup.Init(damage, type);
    }
}